package com.swak.vertx.transport.multipart;

import java.util.Map;

import org.springframework.util.Assert;

import com.swak.Constants;
import com.swak.utils.JaxbMapper;
import com.swak.utils.JsonMapper;
import com.swak.utils.Maps;
import com.swak.vertx.transport.HttpConst;

import io.netty.handler.codec.http.HttpHeaderNames;
import io.netty.util.AsciiString;
import io.vertx.core.http.Cookie;
import lombok.Getter;
import lombok.Setter;
import lombok.experimental.Accessors;

/**
 * 通用的响应输出 : 默认是json输出
 * 
 * @author lifeng
 * @date 2021年3月11日 上午11:08:04
 */
@Getter
@Accessors(chain = true)
public class Response {

	@Setter
	private byte[] data;
	private Cookie cookie;
	@Setter
	private int status = 200;
	private String redirectUrl;
	private Map<AsciiString, CharSequence> headers;

	private Response() {
		this.headers = Maps.newHashMap();
		this.headers.put(HttpHeaderNames.CONTENT_TYPE, HttpConst.APPLICATION_JSON);
	}

	public Response contentType(CharSequence type) {
		Assert.isTrue(type != null, "Type Can Not Be Null");
		this.headers.put(HttpHeaderNames.CONTENT_TYPE, type);
		return this;
	}

	public Response redirect(String redirect) {
		Assert.isTrue(redirect != null, "Redirect Can Not Be Null");
		this.headers.put(HttpHeaderNames.LOCATION, redirect);
		this.status = 302;
		this.data = ("Redirecting to " + redirect + ".").getBytes(Constants.DEFAULT_ENCODING);
		return this;
	}

	public static Response json(Object data) {
		return new Response().setData(JsonMapper.toJson(data).getBytes(Constants.DEFAULT_ENCODING))
				.contentType(HttpConst.APPLICATION_JSON);
	}

	public static Response json(String data) {
		return new Response().setData(data.getBytes(Constants.DEFAULT_ENCODING))
				.contentType(HttpConst.APPLICATION_JSON);
	}

	public static Response text(String data) {
		return new Response().setData(data.getBytes(Constants.DEFAULT_ENCODING))
				.contentType(HttpConst.APPLICATION_TEXT);
	}

	public static Response html(String data) {
		return new Response().setData(data.getBytes(Constants.DEFAULT_ENCODING))
				.contentType(HttpConst.APPLICATION_HTML);
	}

	public static Response xml(Object data) {
		return new Response().setData(JaxbMapper.toXml(data).getBytes(Constants.DEFAULT_ENCODING))
				.contentType(HttpConst.APPLICATION_XML);
	}

	public static Response xml(String data) {
		return new Response().setData(data.getBytes(Constants.DEFAULT_ENCODING)).contentType(HttpConst.APPLICATION_XML);
	}

	public static Response of(String data) {
		return new Response().setData(data.getBytes(Constants.DEFAULT_ENCODING));
	}

	public static Response of(byte[] data) {
		return new Response().setData(data);
	}
}